package cn.xsshome.imagetool.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

/**
 * @author 小帅丶
 * @Description 图片通道转换
 *              readRawImage 适用于微信小程序 实时流 ArrayBuffer 转 BASE64
 * @date 2023/11/14 15:37:22
 */
public class ImageConvertUtil {
    private final static String IMG_PREFIX = "PNG";

    /**
     * @Description RGBA 转为BASE64
     * @param rgbaPixelData
     * @param width - 原图宽
     * @param height - 原图高
     * @Date  2023/11/14  15:31:49
     * @Author 小帅丶
     * @return void
     **/
    public static String readRawImage(byte[] rgbaPixelData, int width, int height) throws IOException {
        ////io流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedImage image = readRawImageConvertBufferedImage(rgbaPixelData,width,height);
        ImageIO.write(image,IMG_PREFIX, baos);
        return Base64Util.encode(baos.toByteArray());
    }

    /**
     * @Description RGBA 另存图片到指定目录
     * @param rgbaPixelData
     * @param width - 原图宽
     * @param height - 原图高
     * @param path - 要保存的路径
     * @Date  2023/11/14  15:31:49
     * @Author 小帅丶
     * @return void
     **/
    public static void readRawImage(byte[] rgbaPixelData, int width, int height, String path) throws IOException {
        BufferedImage image = readRawImageConvertBufferedImage(rgbaPixelData,width,height);
        ImageIO.write(image, IMG_PREFIX, new File(path));
    }

    /**
     * @Description RGBA 转 BufferedImage
     * @param rgbaPixelData
     * @param width - 原图宽
     * @param height - 原图高
     * @Date  2023/11/14 15:33:26
     * @Author 小帅丶
     * @return java.awt.image.BufferedImage
     **/
    public static BufferedImage readRawImageConvertBufferedImage(byte[] rgbaPixelData, int width, int height) {
        //4通道
        int samplesPerPixel = 4;
        //RGBA order
        int[] bandOffsets = {0, 1, 2, 3};

        DataBuffer buffer = new DataBufferByte(rgbaPixelData, rgbaPixelData.length);
        WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height,
                samplesPerPixel * width, samplesPerPixel, bandOffsets, null);
        ColorModel colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), true,
                false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
        BufferedImage image = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);
        return image;
    }
}
